package com.dm.yyxr.config;


import com.dm.yyxr.utils.Result;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.logging.Logger;

/**
 * 全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    /**
     * 用户名重复添加异常处理
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<Object> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            return Result.fail().message("该用户已存在");
        }
        return Result.fail().message("未知错误");
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> exceptionHandler(Exception ex){
        LoggerFactory.getLogger(GlobalExceptionHandler.class).error(ex.getMessage());
        return Result.fail().message(ex.getMessage());
    }
}
